<!-- 我的贴子 -->
<template>
    <el-row style="margin-bottom: 20px;height: auto;margin-left: 20px;">
        <el-col v-for="(item, index) in displayedData" :key="index" :span="16" :offset="index > 0 ? 0 : 0">
            <el-card :body-style="{ padding: '5px' }" style="width: 900px;margin-top: 20px;">
                <div style="padding: 14px">
                    <span>{{ item.postDesc }}</span> <!-- 假设每个对象有一个title属性 -->
                </div>
                <!-- <img v-for="(image, index) in item.postImgs" :key="index" :src="image"
                    style="margin-left: 20px;margin-bottom: 10px;width: 100px;height: 100px;" /> -->
                <!-- 假设每个对象有一个imageUrl属性 -->
                <div style="margin-left: 10px;">
                    <el-button :type="item.buttonType" plain style="width: 100px;" @click="golike(item.postId)">
                        <Pointer style="width: 1em; height: 1em; margin-right: 8px" />点赞&nbsp;<span>{{ item.likeNum
                        }}</span>
                    </el-button>
                    <el-button type="info" plain style="width: 100px;" @click="gocomment(item.postId)">
                        <Comment style="width: 1em; height: 1em; margin-right: 8px" />评论&nbsp;<span>{{
                            item.commentNum }}</span>
                    </el-button>
                    <span style="margin-left: 20px;">作者：{{ item.author }}</span>
                    <el-button type="danger" plain style="width: 50px; margin-left: 10px;"
                        @click="delButton(item.postId)">删除</el-button>
                </div>
            </el-card>

        </el-col>
        <el-dialog v-model="dialogFormVisible" title="删除">
            <p style="font-size: 16px;font-weight: bold;">是否删除该贴子？</p>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="delPost()">
                        确认删除
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </el-row>


    <el-row>
        <!-- 分页 -->
        <div class="paging">
            <el-pagination background layout="prev, pager, next" :total="total" v-model:current-page="currentPage"
                v-model:page-size="pageSize" @current-change="handleCurrentChange" />
        </div>
    </el-row>
</template>
<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import axios from '../../api/index';
import { da, el } from 'element-plus/es/locale';
import { ElMessage } from "element-plus";
import { useRouter } from 'vue-router';
const router = useRouter();



// 从localStorage中获取存储的JSON字符串  
const userInfoJsonString = localStorage.getItem('userInfo')!;

// 解析JSON字符串为JavaScript对象  
const userInfo = JSON.parse(userInfoJsonString);
// import axios from 'axios' // 引入axios库进行HTTP请求  

const dialogFormVisible = ref(false)


const data = reactive([] as any[]) // 用于存储后端传回的数据  

const postId = ref('')

findPosts();

function findPosts() {
    data.splice(0);
    dialogFormVisible.value = false
    if (userInfo.id != null || userInfo.id != '') {

        axios.get('/post/myPosts?userId=' + userInfo.id)
            .then((resp) => {
                if (resp.code = 200) {

                    total.value = resp.data.length;

                    for (let index = 0; index < resp.data.length; index++) {
                        const buttonType = ref('')

                        //根据resp.data[index].userId查询发帖人信息
                        axios.get('/user/' + resp.data[index].userId)
                            .then((resp1) => {
                                if (resp1.code == 2001) {

                                    //查询用户是否点赞
                                    axios.get('/postlike/findPostLike?postId=' + resp.data[index].postId + '&userId=' + userInfo.id)
                                        .then((resp2) => {
                                            if (resp2.code == 200) {
                                                buttonType.value = 'success'
                                            } else {
                                                buttonType.value = 'info'
                                            }
                                            data.push({
                                                postId: resp.data[index].postId,
                                                postImgs: resp.data[index].postImgs,
                                                postDesc: resp.data[index].postContent,
                                                likeNum: resp.data[index].likeNum,
                                                commentNum: resp.data[index].commentNum,
                                                author: resp1.data.nickname,
                                                postLikes: resp.data[index].postLikes,
                                                comments: resp.data[index].comments,
                                                buttonType: buttonType.value
                                            })
                                        })

                                }
                            })

                    }

                }
            })
    }
}

//点赞
function golike(postId: any) {

    //先查询该用户是否点赞了该贴子
    axios.get('/postlike/findPostLike?postId=' + postId + '&userId=' + userInfo.id)
        .then((resp) => {
            // code：200 该用户已经点赞了该贴子
            if (resp.code == 200) {

                //所以点击点赞按钮时，会删除这条点赞
                axios.delete('/postlike/delPostLike?postLikeId=' + resp.data.postLikeId)
                    .then((resp1) => {
                        if (resp1.code == 200) {
                            //删除成功！
                            //重新调用findPosts方法

                            findPosts();
                        } else {
                            //删除失败
                            ElMessage.error('取消点赞失败！')
                        }
                    })
            } else {
                //用呼没有点赞该贴子
                //所以点击时，会添加点赞
                axios({
                    method: 'POST',
                    url: '/postlike/savePostLike',
                    data: JSON.stringify({
                        postId: postId,
                        userId: userInfo.id
                    }),
                    headers: {
                        'Content-Type': 'application/json'
                    }
                }).then((resp2) => {
                    if (resp2.code == 200) {

                        //点赞成功！

                        //重调findPosts方法
                        findPosts();
                    } else {
                        ElMessage.error('点赞失败了！')
                    }
                })

            }
        })
}


//评论
function gocomment(postId: any) {

    //进入评论区
    router.push('/comment/' + postId);

}

//删除按钮
function delButton(item: any) {
    dialogFormVisible.value = true;
    postId.value = item

}


//删除贴子
function delPost() {

    axios.put('/post/deletePost?postId=' + postId.value)
        .then((resp) => {
            if (resp.code == 200) {
                dialogFormVisible.value = false
                ElMessage.success(resp.msg);
                findPosts();

            } else {
                dialogFormVisible.value = false
                ElMessage.error(resp.msg);
            }
        })
}



// 在组件创建时发起HTTP请求获取数据
// function async created() {
//   try {
//     const response = await axios.get('/api/data') // 替换为你的后端API地址
//     data.value = response.data // 将获取到的数据赋值给data变量
//   } catch (error) {
//     console.error(error)
//   }
// }



//分页组件======================

//分页实现
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)

// 监听currentPage和tableData变化，计算显示的数据
const displayedData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return data.slice(start, end);
});

const handleCurrentChange = (val: number) => {
    currentPage.value = val
}



//=========================


</script>